<template>
  <div class="margin-container-list">
    <!-- 操作区域 -->
    <div class="tab-style-default">
      <el-tabs v-model="activeName" class="member-list-tab" @tab-click="handleClick">
        <el-tab-pane label="全部" name=""></el-tab-pane>
        <el-tab-pane label="内部微客" name="2"></el-tab-pane>
        <el-tab-pane label="外部微客" name="1"></el-tab-pane>
      </el-tabs>
    </div>
    <div class="top-operate">
      <div>
        <el-select style="width: 120px" v-model="textCol">
          <el-option label="微客昵称" value="nickname"></el-option>
          <el-option label="微客姓名" value="realName"></el-option>
          <el-option label="手机号" value="phone"></el-option>
        </el-select>
        <el-input style="width: 200px;" v-model="textValue" placeholder="请输入内容"></el-input>
        <el-select v-model="authFlagType" placeholder="是否实名" class="pad-l-10" style="width: 140px">
          <el-option v-for="(value, key) in authFlagList" :key="value" :label="value" :value="key">
          </el-option>
        </el-select>
        <el-date-picker
          v-model="starEndTime"
          type="daterange"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
        <el-select v-model="memberListQuery.wholesaleAuthority" placeholder="批发权限" class="pad-l-10" style="width: 140px">
          <el-option label="全部" value=""></el-option>
          <el-option label="有批发权限" value="1"></el-option>
          <el-option label="无批发权限" value="0"></el-option>
        </el-select>
        <el-button type="primary" @click="handleSearch" style="margin-left: 10px">查询</el-button>
      </div>
    </div>
    <!-- 内容列表 -->
    <div class="pad-b-20">
      <el-button @click="handleCreate" type="primary" v-if="getVersionType() == '1'">添加内部微客</el-button>
      <el-button type="primary" @click="batchOperation('3')" v-if="enterpriseConfig.wholesaleAuthority === 1">开启批发权限</el-button>
      <el-button type="danger" @click="batchOperation('4')" v-if="enterpriseConfig.wholesaleAuthority === 1">关闭批发权限</el-button>
      <!--<el-button @click="distributionSetup" >基本设置</el-button>-->
    </div>
    <div class="table-container">
      <el-table :data="memberList" @sort-change="sortChange" @selection-change="handleSelectionChange"
                v-loading="listLoading" element-loading-text="加载中"
                style="width: 100%">
        <el-table-column width="55px" type="selection" ></el-table-column>
        <el-table-column width="240px" label="微客" prop="userInfo" fixed="left">
          <template slot-scope="scope">
            <div @click="handleUpdate(scope.row)" class="flex v-align-c cursor-p">
              <label><img :src="scope.row.avatar" class="user-avatar" v-if="scope.row.avatar"></label>
              <div class="font-14 pad-l-10">
                <div>昵称：{{scope.row.nickname}}</div>
                <div>姓名：{{scope.row.realName}}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column width="100px" label="微客Id" prop="memberId"></el-table-column>
        <el-table-column width="80px" label="性质" prop="nature" >
          <template slot-scope="scope">
            <span>{{ natureList[scope.row.nature] }}</span>
          </template>
        </el-table-column>
        <!--<el-table-column width="135px" label="标签" prop="labelName">-->
        <!--</el-table-column>-->
        <el-table-column width="150px" label="手机号" prop="phone" >
        </el-table-column>
        <el-table-column width="209px" label="注册时间" prop="taskRegisteredTime" sortable="custom" >
          <template slot-scope="scope">
            <span>{{scope.row.taskRegisteredTime}}</span>
          </template>
        </el-table-column>
        <el-table-column idth="150px" label="批发权限" v-if="enterpriseConfig.wholesaleAuthority === 1">
          <template slot-scope="scope">
            <template v-if="scope.row.wholesaleAuthority == 1"><span>开启</span></template>
            <template v-if="scope.row.wholesaleAuthority == 0"><span>关闭</span></template>
          </template>
        </el-table-column>
        <el-table-column width="150px" label="是否实名" prop="authFlag" >
          <template slot-scope="scope">
            <span>{{ authFlagList[scope.row.authFlag] }}</span>
          </template>
        </el-table-column>
        <el-table-column width="150px" :label="(getVersionType() == 1 || getVersionType() == 3) ? 'TA共赚取酬金' : '分销订单金额'" prop="makeAmount" >
        </el-table-column>
        <el-table-column width="200px" label="备注" prop="remarkName" >
        </el-table-column>
        <el-table-column width="200px" label="操作" align="right" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="medium" @click="handleUpdate(scope.row)">详情</el-button>
            <el-button type="text" size="medium" @click="bindSubUser(scope.row)">设置账号</el-button>
            <el-button type="text" size="medium" @click="editRemark(scope.row)">编辑备注</el-button>
            <!--<el-button v-if="scope.row.taskStatus==1" type="danger"-->
                       <!--@click="handleUpdateStatus(scope.row, 2)" :disabled="isDisabled(scope.row)">禁用-->
            <!--</el-button>-->
            <el-button v-if="scope.row.taskStatus==2"  type="text" size="medium"
                       @click="handleUpdateStatus(scope.row, 1)" :disabled="isDisabled(scope.row)">启用
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 列表分页 -->
    <div class="pagination">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page="memberListQuery.currentPage"
                     :page-sizes="[10, 20, 50, 100]" :page-size="memberListQuery.size"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </div>
    <!-- 添加内部微客弹窗 -->
    <el-dialog title="" :visible.sync="financeVisible" :close-on-press-escape="true" width="400px">
      <div>
        <img :src="enterpriseWxaCode"  style="width: 400px">
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="financeVisible = false">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 分销设置弹窗 -->
    <el-dialog title="" :visible.sync="distributionSetupBoolean" :close-on-press-escape="true" width="600px" :show-close="false">
      <el-tabs v-model="basicStatus" @tab-click="handleClickBasic">
        <el-tab-pane label="分销设置" name="0"></el-tab-pane>
        <el-tab-pane label="批发设置" name="1"></el-tab-pane>
      </el-tabs>
      <template v-if="basicStatus === '0'">
        <div style="background-color: #D9EDF7; color: #36A3F7; border:1px solid #C5DCE7; margin-left: 2%; width: 96%">
          <span style="margin-top: 20px">温馨提示：</span><br/>
          <span>1、开启：</span><br/>
          <span style="margin-left: 10px">a.企业微客可申请分销其他企业的商品，分销成功后您将获得相应的佣金。</span><br/>
          <span style="margin-left: 10px">b.企业微客无法分销与您本企业主营类目一致的商品。</span><br/>
          <span>2、关闭：</span><br/>
          <span style="margin-left: 10px">a.企业微客只能分销您的商品。</span><br/>
          <span style="margin-left: 10px">b.如果在您之前开启的过程中企业微客有申请分销其他企业，并且通过后将企业商品上架到店铺中售卖，则在您关闭后上架的商品将会保留在您的企业微客店铺中。</span><br/>
        </div>
        <div style="margin-left: 20px; margin-top: 20px">
          <el-switch
            v-model="distributionType"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch><span style="font-size: 20px; margin-left: 10px">开关</span>
          <span style="color: red" v-if="distributionType === false">(已关闭)</span>
          <span style="color: deepskyblue" v-if="distributionType === true">(已开启)</span>
        </div>
      </template>
      <template v-if="basicStatus === '1'">
        <div style="background-color: #D9EDF7; color: #36A3F7; border:1px solid #C5DCE7; margin-left: 2%; width: 96%">
          <span style="margin-top: 20px">温馨提示：</span><br/>
          <span style="margin-left: 10px">1、开启：成为企业内部、外部微客后将自动获得批发权限。</span><br/>
          <span style="margin-left: 10px">2、关闭：成为企业内部、外部微客后将没有批发权限。</span><br/>
        </div>
        <div style="margin-left: 20px; margin-top: 20px">
          <el-switch
            v-model="memberWholesaleAuthority"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch><span style="font-size: 20px; margin-left: 10px">开关</span>
          <span style="color: red" v-if="memberWholesaleAuthority === false">(已关闭)</span>
          <span style="color: deepskyblue" v-if="memberWholesaleAuthority === true">(已开启)</span>
        </div>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button @click="saveDistributionType" type="primary">保存设置</el-button>
        <el-button @click="distributionSetupBoolean = false">关闭</el-button>
      </div>
    </el-dialog>
    <el-dialog title="设置账号" :visible.sync="setSubUserVisible" :close-on-press-escape="true" width="550px">
      <el-form :model="subUser" label-width="150px" :rules="rules" ref="subUser">
        <el-form-item label="昵称" prop="nickname">
          <div>{{subUser.nickname}}</div>
        </el-form-item>
        <el-form-item label="操作员姓名" prop="username">
          <div><el-input v-model="subUser.username" placeholder="请输入操作员姓名" style="width: 300px"></el-input></div>
        </el-form-item>
        <el-form-item label="登录手机号" prop="phone">
          <div><el-input  v-model="subUser.phone" type="tel" placeholder="请输入手机号"  maxlength="11"
                          oninput="this.value=this.value.replace(/^[0,2,3,4,5,6,7,8,9]*$/gi,'')"
                          onkeyup="this.value=this.value.replace(/\D/g,'')" style="width: 300px"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="所属角色" prop="subRoleId">
          <div>
            <el-select v-model="subUser.subRoleId" placeholder="请选择" >
              <el-option v-for="(item, index) in subRoleList" :key="item.subRoleId" :label="item.name" :value="item.subRoleId"/>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio v-model="subUser.status" label="1">启用</el-radio>
          <el-radio v-model="subUser.status" label="0">禁用</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="setSubUserVisible = false">取消</el-button>
        <el-button type="primary" @click="doBindSubUser">保存</el-button>
      </div>
    </el-dialog>

    <!-- 拒绝通过 -->
    <el-dialog title="备注" :visible.sync="remarkVisible" :close-on-press-escape="true" width="460px">
      <div style="padding:20px;">
        <el-input
          type="textarea"
          :rows="6"
          placeholder="请输入内容"
          v-model="memberRemark.remarkName">
        </el-input>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRemark">确认</el-button>
        <el-button @click="remarkVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<style scoped>
  .user-avatar{
    width: 46px;
    height: 46px;
    display: block;
    border-radius: 50px;
  }
</style>

<script>
  import { getNameByPath } from '@/utils/get-name-by-path' // 不要删除，根据URL获取文件名
  import { pageMember, enableDisable, bacthUpdate, bacthUpdateAuthority, doBindSubUser, saveMemberRemark, getBindSubUser } from '@/api/user/member'
  import { doNatureInWxaCode, updateDistributionType, getEnterprise } from '@/api/user/enterprise'
  import { getByEnterpriseId } from '@/api/user/enterprise'

  import elDragDialog from '@/directive/el-dragDialog' // base on element-ui
  import store from '@/store'
  import Detail from '../../../components/Member/Detail'
  import { listEnterpeiseRole } from '@/api/system/role'

  export default {
    name: getNameByPath(),
    components: {
      Detail
    },
    directives: {
      // 拖动窗口
      elDragDialog
    },
    data() {
      return {
        basicStatus: '0',
        memberList: [],
        textCol: 'nickname',
        textValue: '',
        starEndTime: [],
        th_memberList: [],
        authFlagList: [],
        natureList: [],
        authFlagType: '',
        activeName: '',
        total: null,
        distributionType: '',
        memberWholesaleAuthority: '',
        distributionSetupBoolean: false,
        setSubUserVisible: false,
        listLoading: true,
        financeVisible: false,
        remarkVisible: false,
        keyword: '',
        keywordTypeOld: '',
        multipleSelection: [],
        memberListQuery: {
          currentPage: 1,
          size: 10,
          startDate: null,
          endDate: null,
          nature: '',
          taskStatus: '',
          authFlag: '',
          enterpriseId: '',
          recruiterId: ''
        },
        member: {
          memberId: '',
          nickname: '',
          realName: '',
          nature: '',
          memberGrade: '',
          labelName: '',
          phone: '',
          taskRegisteredTime: '',
          authFlag: '',
          taskStatus: '',
          delFlag: '',
          enterpriseId: '',
          status: '0'
        },
        enterpriseConfig: {
          wholesaleAuthority: 0
        },
        subUser: {
          memberId: ''
        },
        subRoleList: [],
        rules: {
          phone: [
            { required: true, message: '请输入手机号', trigger: 'blur' }
          ],
          subRoleId: [
            { required: true, message: '请选择角色', trigger: 'blur' }
          ],
          username: [
            { required: true, message: '请输入操作员姓名', trigger: 'blur' }
          ]
        },
        memberAuthority: {},
        memberRemark: {
          memberRemarkId: '',
          remarkType: 1,
          remarkName: '',
          memberId: '',
          userId: this.getEnterpriseId()
        },
        enterpriseWxaCode: '',
        natureStyleMap: {
          0: 'font-yellow',
          1: 'font-blue',
          2: 'font-green'
        },
        authFlagStyleMap: {
          0: 'font-orange',
          1: 'font-green'
        }
      }
    },
    // 过滤器
    filters: {
      statusFilter(status) {
        const statusMap = {
          1: 'success',
          2: 'danger'
        }
        return statusMap[status]
      }
    },
    // 初始化页面
    created() {
      this.queryParams = this.getCurrentPage().query
      if (this.queryParams && this.queryParams.recruiterId) {
        this.memberListQuery.recruiterId = this.queryParams.recruiterId.toString()
      }
      this.initConfig()
      this.initMemberList()
      this.listEnterpeiseRole()
    },
    methods: {
      initConfig() {
        getByEnterpriseId(this.getEnterpriseId()).then(response => {
          if (response.isError) return
          this.enterpriseConfig = response.data
        })
      },
      listEnterpeiseRole() {
        listEnterpeiseRole({ enterpriseId: this.getEnterpriseId(), memberFlag: 1 }).then(response => {
          if (response.isError) return
          this.subRoleList = response.data
        })
      },
      handleCommand(command) {
        this.batchOperation(command)
      },
      initMemberList() {
        this.listLoading = true
        this.memberListQuery.enterpriseId = this.getEnterpriseId()
        this.memberListQuery.nickname = ''
        this.memberListQuery.realName = ''
        this.memberListQuery.phone = ''
        this.memberListQuery[this.textCol] = this.textValue
        pageMember(this.memberListQuery).then(response => {
          if (response.isError) return
          this.memberList = response.data.records
          if (this.memberList) {
            for (let i = 0; i < this.memberList.length; i++) {
              this.memberList[i].userInfo = {}
              this.memberList[i].userInfo.avatar = this.memberList[i].avatar
              this.memberList[i].userInfo.nickname = this.memberList[i].nickname
              this.memberList[i].userInfo.realName = this.memberList[i].realName
              this.memberList[i].natureStyle = this.natureStyleMap[this.memberList[i].nature]
              this.memberList[i].authFlagStyle = this.authFlagStyleMap[this.memberList[i].authFlag]
            }
          }
          if (this.memberList != null && this.memberList.length > 0) {
            if (response.data.dict.authFlag != null) {
              this.authFlagList = response.data.dict.authFlag
              this.authFlagList[''] = '实名状态'
            }
            if (response.data.dict.nature != null) {
              this.natureList = response.data.dict.nature
            }
          }
          this.total = response.data.total
          this.listLoading = false
        })
      },
      // 列表排序
      sortChange(data) {
        const { prop, order } = data
        if (prop === 'createTime') {
          if (order === 'ascending') {
            this.memberListQuery.ascs = 'createTime'
            this.memberListQuery.descs = ''
          } else {
            this.memberListQuery.ascs = ''
            this.memberListQuery.descs = 'createTime'
          }
        }
        this.initMemberList()
      },
      handleClick() {
        this.memberListQuery.taskStatus = ''
        this.memberListQuery.nature = ''
        if (this.activeName === '3') {
          this.memberListQuery.taskStatus = '2'
        }
        if (this.activeName === '1') {
          this.memberListQuery.nature = this.activeName
        }
        if (this.activeName === '2') {
          this.memberListQuery.nature = this.activeName
        }
        this.initMemberList()
      },
      handleClickBasic() {
      },
      handleSearch() {
        // this.searchReset()
        this.memberListQuery.currentPage = 1
        if (this.starEndTime) {
          if (this.starEndTime.length > 0) {
            this.memberListQuery.startDate = this.starEndTime[0]
            this.memberListQuery.endDate = this.starEndTime[1]
          }
        }
        this.memberListQuery.authFlag = this.authFlagType
        this.initMemberList()
      },
      searchReset() {
        this.memberListQuery = {
          currentPage: 1,
          size: 10,
          startDate: null,
          endDate: null,
          nature: '',
          taskStatus: '',
          authFlag: ''
        }
      },
      handleSizeChange(val) {
        this.memberListQuery.size = val
        this.initMemberList()
      },
      handleCurrentChange(val) {
        this.memberListQuery.currentPage = val
        this.initMemberList()
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
        this.th_memberList = []
      },
      // 添加内部微客
      handleCreate() {
        const data = {
          enterpriseId: this.getEnterpriseId()
        }
        doNatureInWxaCode(data).then(response => {
          if (response.isError) return
          this.enterpriseWxaCode = response.data
          this.financeVisible = true
        })
      },
      // 设置账户
      bindSubUser(row) {
        getBindSubUser(row.memberId).then(response => {
          if (response.isError) return
          this.subUser = response.data
          this.subUser.status = this.subUser.status ? this.subUser.status + '' : '1'
          this.subUser.nickname = row.nickname
          this.subUser.memberId = row.memberId
          this.setSubUserVisible = true
        })
      },
      // 设置账户
      editRemark(row) {
        this.memberRemark.memberRemarkId = row.memberRemarkId
        this.memberRemark.memberId = row.memberId
        this.memberRemark.remarkName = row.remarkName
        this.memberRemark.remarkType = '4'
        this.memberRemark.userId = this.getEnterpriseId()
        this.remarkVisible = true
      },
      submitRemark() {
        saveMemberRemark(this.memberRemark).then(response => {
          if (response.isError) return
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          this.remarkVisible = false
          this.initMemberList()
        })
      },
      // 设置账户
      doBindSubUser() {
        this.$refs['subUser'].validate((valid) => {
          if (valid) {
            this.subUser.enterpriseId = this.getEnterpriseId()
            doBindSubUser(this.subUser).then(response => {
              if (response.isError) return
              this.$message({
                type: 'success',
                message: '成功!'
              })
              this.setSubUserVisible = false
            })
          }
        })
      },
      // 详情
      handleUpdate(row) {
        this.$router.push({ path: '/user/member/details/index', query: { memberId: row.memberId, enterpriseId: this.getEnterpriseId() }})
      },
      distributionSetup() {
        getEnterprise(this.getEnterpriseId()).then(response => {
          if (response.isError) return
          if (response.data.distributionType === 0) {
            this.distributionType = false
          }
          if (response.data.distributionType === 1) {
            this.distributionType = true
          }
          if (response.data.memberWholesaleAuthority === 0) {
            this.memberWholesaleAuthority = false
          }
          if (response.data.memberWholesaleAuthority === 1) {
            this.memberWholesaleAuthority = true
          }
          this.basicStatus = '0'
          this.distributionSetupBoolean = true
        })
      },
      saveDistributionType() {
        let type = 0
        if (this.distributionType === true) {
          type = 1
        }
        let memberType = 0
        if (this.memberWholesaleAuthority === true) {
          memberType = 1
        }
        const data = {
          enterpriseId: this.getEnterpriseId(),
          distributionType: type,
          memberWholesaleAuthority: memberType
        }
        updateDistributionType(data).then(response => {
          if (response.isError) return
          this.$message({
            message: '成功',
            type: 'success'
          })
          this.distributionSetupBoolean = false
        })
      },
      // 更新
      handleUpdateStatus(row, status) {
        this.resetMember()
        this.member = Object.assign(this.member, row)
        this.member.taskStatus = status
        let name = ''
        if (status === 2) {
          name = '禁用成功!'
        } else {
          name = '启用成功!'
        }
        enableDisable(this.member).then((response) => {
          if (response.isError) return
          this.$message({
            type: 'success',
            message: name
          })
          this.initMemberList()
        })
      },
      isDisabled(row) {
        // 不能锁定、删除自己
        return row.username === store.getters.username
      },
      // 重置member
      resetMember() {
        this.member = {
          memberId: '',
          nickname: '',
          realName: '',
          nature: '',
          memberGrade: '',
          labelName: '',
          phone: '',
          taskRegisteredTime: '',
          authFlag: '',
          taskStatus: '',
          delFlag: ''
        }
      },
      // 批量操作
      batchOperation(command) {
        if (this.multipleSelection.length > 0) {
          if (command === '1' || command === '2') {
            this.multipleSelection.forEach((item) => {
              this.resetMember()
              this.member.memberId = item.memberId
              if (command === '') {
                this.member.delFlag = 1
              } else {
                this.member.taskStatus = command
              }
              this.th_memberList.push(this.member)
            })
            bacthUpdate(this.th_memberList).then(response => {
              if (response.isError) return
              this.initMemberList()
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
            })
          } else {
            this.multipleSelection.forEach((item) => {
              this.memberAuthority = {}
              this.memberAuthority.memberId = item.memberId
              this.memberAuthority.enterpriseId = this.getEnterpriseId()
              if (command === '3') {
                this.memberAuthority.wholesaleAuthority = 1
              }
              if (command === '4') {
                this.memberAuthority.wholesaleAuthority = 0
              }
              this.th_memberList.push(this.memberAuthority)
            })
            bacthUpdateAuthority(this.th_memberList).then(response => {
              if (response.isError) return
              this.initMemberList()
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
            })
          }
          this.th_memberList = []
        } else {
          this.$message.error('请选择要操作的数据')
        }
      }
    },
    mounted() {

    }
  }
</script>
